package com.example.jobtask.service;

import cn.dev33.satoken.stp.StpUtil;
import com.example.jobtask.dto.LoginRequest;
import com.example.jobtask.dto.RegisterRequest;
import com.example.jobtask.dto.UserInfoResponse;
import com.example.jobtask.entity.SysUser;
import com.example.jobtask.repository.SysUserRepository;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 系统用户服务类
 */
@Service
@Transactional
public class SysUserService {
    
    @Autowired
    private SysUserRepository userRepository;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    /**
     * 用户登录
     */
    public Map<String, Object> login(LoginRequest loginRequest, HttpServletRequest request) {
        String loginId = loginRequest.getLoginId();
        String password = loginRequest.getPassword();
        
        // 查找用户
        Optional<SysUser> userOpt = userRepository.findByUsernameOrEmail(loginId);
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        SysUser user = userOpt.get();
        
        // 检查用户状态
        if (!user.getStatus()) {
            throw new RuntimeException("用户已被禁用");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 更新最后登录信息
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(getClientIpAddress(request));
        userRepository.save(user);
        
        // Sa-Token登录
        StpUtil.login(user.getId());
        
        // 设置用户角色
        StpUtil.getSession().set("role", user.getRole());
        
        // 设置记住我
        if (loginRequest.getRememberMe() != null && loginRequest.getRememberMe()) {
            StpUtil.renewTimeout(60 * 60 * 24 * 30); // 30天
        }
        
        // 返回登录信息
        Map<String, Object> result = new HashMap<>();
        result.put("token", StpUtil.getTokenValue());
        result.put("userInfo", new UserInfoResponse(user));
        result.put("message", "登录成功");
        
        return result;
    }
    
    /**
     * 用户注册
     */
    public Map<String, Object> register(RegisterRequest registerRequest) {
        // 验证密码确认
        if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }
        
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(registerRequest.getEmail())) {
            throw new RuntimeException("邮箱已被注册");
        }
        
        // 创建新用户
        SysUser user = new SysUser();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setEmail(registerRequest.getEmail());
        user.setRealName(registerRequest.getRealName());
        user.setPhone(registerRequest.getPhone());
        user.setStatus(true);
        user.setRole("USER");
        
        // 保存用户
        user = userRepository.save(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", new UserInfoResponse(user));
        result.put("message", "注册成功");
        
        return result;
    }
    
    /**
     * 获取当前登录用户信息
     */
    public UserInfoResponse getCurrentUserInfo() {
        // 检查是否已登录
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("用户未登录");
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<SysUser> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        return new UserInfoResponse(userOpt.get());
    }
    
    /**
     * 用户登出
     */
    public Map<String, Object> logout() {
        StpUtil.logout();
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "登出成功");
        
        return result;
    }
    
    /**
     * 修改密码
     */
    public Map<String, Object> changePassword(String oldPassword, String newPassword) {
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("用户未登录");
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<SysUser> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        SysUser user = userOpt.get();
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "密码修改成功");
        
        return result;
    }
    
    /**
     * 更新用户信息
     */
    public Map<String, Object> updateUserInfo(String realName, String phone, String avatar) {
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("用户未登录");
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<SysUser> userOpt = userRepository.findById(userId);
        
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        SysUser user = userOpt.get();
        
        // 更新用户信息
        if (StringUtils.hasText(realName)) {
            user.setRealName(realName);
        }
        if (StringUtils.hasText(phone)) {
            user.setPhone(phone);
        }
        if (StringUtils.hasText(avatar)) {
            user.setAvatar(avatar);
        }
        
        user = userRepository.save(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", new UserInfoResponse(user));
        result.put("message", "用户信息更新成功");
        
        return result;
    }
    
    /**
     * 根据用户ID获取用户信息
     */
    public SysUser getUserById(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(xForwardedFor) && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (StringUtils.hasText(xRealIp) && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}